package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock {
    private static final String KEY_PREFIX = "lock:";
    private StringRedisTemplate stringRedisTemplate;
    private String ID_PREFIX = UUID.randomUUID().toString();
    private String name;
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
    }

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    // 获取锁
    public boolean tryLock(long timeoutSec) {
        // 获取线程标识
        String currentId = ID_PREFIX + "-" + Thread.currentThread().getId();
        // 获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, currentId,
            timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(success);
    }

    // 释放锁
    public void unlock() {
        // // 使用lua脚本完成原子性
        stringRedisTemplate.execute(
            UNLOCK_SCRIPT,
            Collections.singletonList(KEY_PREFIX + name),
            ID_PREFIX + Thread.currentThread().getId()
        );


        // 判断当前线程ID和存进去的是不是一样，如果一样删除
        // String threadId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        // String currentId = ID_PREFIX + "-" + Thread.currentThread().getId();
        // if(currentId.equals(threadId)) {
        //     stringRedisTemplate.delete(KEY_PREFIX + name);
        // }
    }
}
